import { defineStore } from 'pinia';
import { getRandomFiles } from '../api/study/bizFilesController';
import { useRadio } from 'element-plus/es/components/radio/src/use-radio.mjs';
import { getUsernameById } from '../api/study/sysUserController';
// 获取环境变量中的视频前缀
const VIDEO_BASE_URL = import.meta.env.VITE_MINIO_URL;
export const useObtainVideoStore = defineStore('obtainVideo', {
  state: () => ({
    videoFiles: [],
    isLoading: false,
    error: null as string | null
  }),
  
  actions: {
    /**
     * 获取随机视频文件
     * @param limit 视频数量限制
     * @returns 视频列表
     */
    async fetchRandomVideos(limit: number ) {
      this.isLoading = true;
      this.error = null;
      
      try {
        const response = await getRandomFiles({ limit });
        if (response?.data) {
          // 转换接口数据为前端所需格式
          this.videoFiles = response.data.map((file: any) => ({
            id: file.id,
            videoUrl:VIDEO_BASE_URL+ file.previewUrl, // 假设接口返回的视频地址字段为url
            title: file.fileName || '未命名视频', // 假设接口返回的标题字段为name
            likeCount: file.likeCount || 0,
            commentCount: file.commentCount || 0,
            comments: file.comments || [],
            viewCount: file.viewCount || 0,
            isLiked: false,
            currentTime: 0,
            duration: 0,
            progress: 0,
            bufferProgress: 0,
            userId: file.userId,
            nickname: '', // 新增用户名字段
            avatar:'',
            worksName:file.worksName,//课程名
            description:file.description,//介绍
          }));
          // 遍历视频列表，获取每个视频对应的用户名
          for (const video of this.videoFiles) {
            if (video.userId) {
              try {
                const usernameResponse = await getUsernameById({ userId: video.userId });
                if (usernameResponse.data) {
                  video.nickname = usernameResponse.data.nickname;
                  video.avatar=VIDEO_BASE_URL+usernameResponse.data.avatar;
                } else {
                  video.nickname = '未知用户';
                }
              } catch (err) {
                console.error(`获取用户ID为${video.userId}的用户名失败:`, err);
                video.nickname = '获取失败';
              }
            } else {
              video.nickname = '匿名用户';
            }
          }


          return this.videoFiles;
        }
        return [];
      } catch (err) {
        this.error = err instanceof Error ? err.message : '获取视频失败';
        console.error('获取视频失败:', err);
        return [];
      } finally {
        this.isLoading = false;
      }
    }
  }
});